package com.thb.user.service.Impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.thb.configure.config.Config;
import com.thb.exception.ServiceException;
import com.thb.user.dao.IUserInfoDAO;
import com.thb.user.model.UserInfo;
import com.thb.user.service.IUserCodeService;
import com.thb.user.service.IUserInfoService;

@Service
public class UserInfoServiceImpl implements IUserInfoService {
	
	private static final Logger logger = LoggerFactory.getLogger(UserInfoServiceImpl.class);
	
	@Autowired
	private IUserInfoDAO userInfoDao;
	
	@Autowired
	private IUserCodeService userCodeService;
	
	@Autowired
	private Config config;

	@Override
	public boolean add(UserInfo info) {
		logger.info("add info:{}",JSONObject.toJSONString(info));
		UserInfo info1 = findInfoByUid(info.getUid());
		if(info1 != null){
			throw new ServiceException("2000", "用户信息已存在");
		}
		return addInfo(info);
	}

	@Override
	public boolean update(UserInfo info,int uid) {
		UserInfo info1 = findInfoByUid(uid);
		if(info1 == null){
			info.setUid(uid);
			addInfo(info);
		}else{
			info.setUid(uid);
			updateInfo(info);
		}
		return true;
	}

	@Override
	public UserInfo findInfoByUid(int uid) {
		UserInfo info = userInfoDao.findInfoByUid(uid);
		return info;
	}
	
	private boolean addInfo(UserInfo info){
		userInfoDao.insert(info);
		return true;
	}
	
	private boolean updateInfo(UserInfo info){
		userInfoDao.update(info);
		return true;
	}

	/*@Override
	public boolean add(String email, String passwd,int usertype) {
		isRegister(email);
		String uid = UUID.randomUUID().toString();
		String nick = userCodeService.getNick();
		addUser(uid, email,passwd,usertype,nick);
		userCodeService.add(uid, passwd, UserConstant.utype_email, email);
		userCodeService.add(uid, passwd, UserConstant.utype_nick, nick);
		return true;
	}

	@Override
	public boolean isRegister (String email) {
		UserCode user = userCodeService.findInfoByUsercode(email);
		if(user != null){
			throw new ServiceException(ExceptionCodeUtil.CommonErrorCode, "用户已经注册");
		}
		return false;
	}
	
	@Override
	public UserVO findUserByUid(String uid){
		logger.info(String.format("UserVO findUserByUid [ %s ] ", uid));
		Object object = MemcachedUtil.get(MKeyUtils.getUserUidKey(uid));
		UserVO user = null;
		
		if(object != null && !(object instanceof NullObject)){
			logger.info(String.format("find user from  [ %s ] ", "memcached"));
			return (UserVO)object;
		}else if(object == null){
			logger.info(String.format("find user from %s", "database"));
			user = userDao.findUserByUid(uid);
			MemcachedUtil.set(MKeyUtils.getUserUidKey(uid), user!=null?user:NullObject.nullObject);
		}
		
		return user;
	}
	
	private boolean addUser(String uid,String email,String passwd,int usertype,String nickName){
		logger.info("------- addUser---");
		
		userDao.insert(uid, email, passwd,usertype,nickName);
		MemcachedUtil.remove(MKeyUtils.getUserKey(email));
		return true;
	
	}

	@Override
	public String login(String email, String passwd,int usertype) {
		UserCode user = userCodeService.findInfoByUsercode(email);
		if(user==null){
			throw new ServiceException(ExceptionCodeUtil.CommonErrorCode, "用户名或密码错误");
		}
		
		if(!user.getPasswd().equals(passwd)){
			throw new ServiceException(ExceptionCodeUtil.CommonErrorCode, "用户名或密码错误");
		}
		
		if(user.getUserType().intValue() != usertype){
			throw new ServiceException(ExceptionCodeUtil.CommonErrorCode, "用户名或密码错误");
		}
		
		String sid = UUID.randomUUID().toString();
		
		MemcachedUtil.set(MKeyUtils.getSidUserKey(sid), MKeyUtils.Sid_Default_Time, user);
		return sid;
	}
	
	@Override
	public boolean updateUser(UserInfo info,User user){
		this.updateUserInfo(info);
		this.updateUser(user);
		return true;
	}

	private boolean updateUserInfo(UserInfo userInfo) {
		logger.info("------- updateUserInfo---");
		userDao.update(userInfo);
		MemcachedUtil.remove(MKeyUtils.getUserInfoKey(userInfo.getUserId()));
		return true;
	}
	
	@Override
	public UserInfo findInfoByUid(String uid){
		logger.info(String.format("%s:%s","------- findInfoByUid---",uid));
		Object object = MemcachedUtil.get(MKeyUtils.getUserInfoKey(uid));
		UserInfo user = null;
		
		if(object != null && !(object instanceof NullObject)){
			logger.info(String.format("find userinfo from %s", "memcached"));
			return (UserInfo)object;
		}else if(object == null){
			logger.info(String.format("find userinfo from %s", "database"));
			user = userDao.findInfoByUid(uid);
			if(user.getCollegeCode()!= null && !"".equals(user.getCollegeCode())){
				List<Community> cList = acadeService.findAllIn();
				for(Community c:cList){
					if(c.getCommunityId().equals(user.getCollegeCode())){
						user.setCollegeName(c.getName());
						
						List<Department> dList = departmentService.findByCommunityId(c.getCommunityId());
						for(Department d:dList){
							if(d.getDepartmentCode().equals(user.getDepartmentCode())){
								user.setDepartmentName(d.getName());
							}
						}
					}
				}
			}
			MemcachedUtil.set(MKeyUtils.getUserInfoKey(uid), user!=null?user:NullObject.nullObject);
		}
		
		return user;
		
	}
	
	@Override
	public JSONObject findUserCenter(String uid){
		
		UserInfo info = findInfoByUid(uid);
		if(info == null){
			throw new ServiceException(ExceptionCodeUtil.InnerErrorCode, "处理数据失败");
		}
		User user = findUserByUid(uid);
		
		JSONObject obj = new JSONObject();
		obj.put("userId", user.getUserId());
		obj.put("nickName", user.getNickName());
		obj.put("email", user.getEmail());
		obj.put("collegeName", info.getCollegeName());
		obj.put("sign", info.getSign());
		obj.put("headeImage", user.getHeadImage());
		obj.put("cellPhome", info.getCellPhone());
		obj.put("sex",info.getSex());
		obj.put("departmentName",info.getDepartmentName());
		obj.put("className",info.getClassName());
		
		return obj;
	}

	private boolean updateUser(User user) {
		logger.info(String.format("%s:%s","------- updateUser---",user.getUserId()));
		if(user.getHeadImage() != null && !user.getHeadImage().equals("")){
			String file = ImageUtils.GenerateImage(user.getHeadImage(),config.getHeadImgUrl());
			user.setHeadImage(file);
		}
		userDao.update(user);
		if(user.getNickName() != null && !user.getNickName().equals("")){
			userCodeService.updateUserNick(user.getUserId(), user.getNickName());
		}
		
		MemcachedUtil.remove(MKeyUtils.getUserKey(user.getEmail()));
		return true;
	}

	@Override
	public boolean updatePasswd(User user, String passwd) {
		updatePwd(user.getUserId(), passwd, user.getEmail(),user.getNickName());
		return true;
	}
	
	private int updatePwd(String uid, String passwd,String email,String nick){
		userCodeService.updatePasswd(uid, passwd, email, nick);
		return 1;
	}

	@Override
	public boolean forgetPasswd(String email) {
		logger.info(String.format("%s:%s","forgetPasswd ",email));
		UserCode vo = userCodeService.findInfoByUsercode(email);
		if(vo == null){
			throw new ServiceException(ExceptionCodeUtil.CommonErrorCode, "当前用户未注册");
		}
		String random = RandomUtils.getRandom(6);
		MemcachedUtil.set(MKeyUtils.getForgetPasswdKey(email), UserConstant.RandomExpireTime, random);
		boolean isSend = MailUtils.SendPasswdMail(config,email, random, UserConstant.RandomExpireTime/60);
		if(!isSend){
			throw new ServiceException(ExceptionCodeUtil.CommonErrorCode, "邮件发送失败，请稍后重试");
		}
		logger.info(String.format("%s:%s","forgetPasswd end",email));
		return true;
	}*/
	

}
